﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.IsolatedStorage;
using System.Net;
using Coding4Fun.Toolkit.Controls;
using Microsoft.Phone.Reactive;
using Microsoft.Phone.Shell;
using Newtonsoft.Json;
using _300Report.Pages;

namespace _300Report.Global
{
    /// <summary>
    /// 全局方法
    /// </summary>
    class Config
    {

        /// <summary>
        /// 表示当前是否具有网路
        /// </summary>
        public static bool IsNetworkRunning
        {
            get
            {
                return PhoneApplicationService.Current.State.ContainsKey("IsNetworkRunning") ?
                    (bool)PhoneApplicationService.Current.State["IsNetworkRunning"] : false;
            }
            set { PhoneApplicationService.Current.State["IsNetworkRunning"] = value; }
        }

        /// <summary>
        /// 检查网络状态
        /// </summary>
        public static bool CheckNetworkState()
        {
            return Microsoft.Phone.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();
        }

        public static void NetWorkUnaviliableToast()
        {
                ToastPrompt toastPrompt = new ToastPrompt();
                toastPrompt.Message = "未检测到网络,无法查找,请打开网络";
                toastPrompt.MillisecondsUntilHidden = 1800;
                toastPrompt.Show();
        }

        /// <summary>
        /// 解析Json,泛型
        ///  </summary>
        /// <param name="res"></param>
        /// <returns></returns>
        public static T PareseHeroReport<T>(string res)
        {
            if (string.IsNullOrEmpty(res))
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(res);
        }

        /// <summary>
        /// 获取网络请求字符串内容
        /// </summary>
        //public static Func<string, IObservable<string>> HttpGetStringResult = url =>
        //{
        //    var request = HttpWebRequest.Create(new Uri(url));
        //    var result = Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse);
        //    return result().Select(res => WebResponseToString(res));
        //};

        public static IObservable<string> HttpGetStringResult(string url)
        {
            var request = HttpWebRequest.Create(new Uri(url));
            var result = Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse);
            return result().Select(res => WebResponseToString(res));
        }

        private static string WebResponseToString(WebResponse webResponse)
        {

             HttpWebResponse response = (HttpWebResponse)webResponse;
            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                return reader.ReadToEnd();
            }

        }


        /// <summary>
        /// 全局提示信息
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="timeMillonseconds"></param>
        public static void Toast(string msg, int timeMillonseconds)
        {
            ToastPrompt toastPrompt = new ToastPrompt();
            toastPrompt.Message = msg;
            toastPrompt.MillisecondsUntilHidden = timeMillonseconds;
            toastPrompt.Show();
        }

        /// <summary>
        /// 秒转分+秒
        /// </summary>
        /// <param name="seconds"></param>
        /// <returns></returns>
        public static string GetSeconds2Minutes(int seconds)
        {
            return string.Format("{0}分{1}秒",seconds/60,seconds%60);
        }

        /// <summary>
        /// settting缓存
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T GetIsolatedStorageSettings<T>(string key)
        {
            try
            {
                return (T)IsolatedStorageSettings.ApplicationSettings[key];
            }
            catch (Exception e)
            {
                return default(T);
            }
        }

        public static void SetIsolatedStorageSettings(string key,object value)
        {
           IsolatedStorageSettings s = IsolatedStorageSettings.ApplicationSettings;
           s[key] = value;
           s.Save(); 
         
        }

        public static bool ClearIsolatedStorageSettings(string key)
        {
            try
            {
                return IsolatedStorageSettings.ApplicationSettings.Remove(key);
            }
            catch (Exception e)
            {
                return false;
            }
        }


        public static SortedSet<string> GetSearchReportHistory()
        {
            SortedSet<string> request = Config.GetIsolatedStorageSettings<SortedSet<string>>(SearchReportHistoryPage.SearcHistoryKey);
            if (request != null && request.Count > 0)
            {
                return request;
            }
            else
            {
                return null;
            }
        }
    }
}
